---@class BehaviourTreesBuilder
local BehaviourTreesBuilder = ClientFight.CreateClass("BehaviourTreesBuilder")
local START = "开始"
local SEQUENCE = "序列"
local SELECTOR = "选择器"
---@return BehaviourTree
function BehaviourTreesBuilder:build(fight,fighter,jsonObj)
    ---@type BehaviourTree
    local tree = BehaviourTree.New()
    local root = jsonObj[START]
    for k,entry in pairsByKeys(root) do
        tree.root = self:createNode(fight,fighter,k,entry)
    end
    return tree
end
---@return IBehaviour
function BehaviourTreesBuilder:createNode(fight,fighter,key,value)
  local keyStart = string.find(key,"-") + 1
   local  newKey = string.sub(key,keyStart);
    if string.startsWith(newKey,SEQUENCE) then
        ---@type Sequence
        local sequence = Sequence.New()
        local objs = value
        if type(objs) == "table" then
            for k,entry in pairsByKeys(objs) do
                sequence:addChild(self:createNode(fight,fighter,k,entry))
            end
            return sequence
        end
    elseif string.startsWith(newKey,SELECTOR) then
        ---@type Selector
        local selector = Selector.New()
        local objs = value
        if type(objs) == "table" then
            for k,entry in pairsByKeys(objs) do
                selector:addChild(self:createNode(fight,fighter,k,entry))
            end
            return selector
        end
    else
        return self:createLeaf(fight,fighter,key,value)
    end
end
function BehaviourTreesBuilder:createLeaf(fight,fighter,key,value)
    for k,_type in pairsByKeys(ConditionAndActionTypeEnum:values()) do
        local keyStart = string.find(key,"-") + 1
        local  newKey = string.sub(key,keyStart);
        if string.startsWith(newKey,_type:getName()) then
            ---@type AbstractLeaf
            local leaf = _type:getClazz().New()
            leaf.fight = fight
            leaf.fighter = fighter
            return leaf
        end
    end
    logError("BehaviourTreeNonActionOrConditionException: error key "..tostring(key))
end